package com.kmxy.kmxy_base

import android.Manifest
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.location.GpsSatellite
import android.location.GpsStatus
import android.location.LocationManager
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import androidx.annotation.NonNull
import androidx.annotation.RequiresApi
import com.amap.api.location.AMapLocation
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import org.json.JSONObject

/** KmxyBasePlugin */
class KmxyBasePlugin: FlutterPlugin, MethodCallHandler, ActivityAware {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel
  private lateinit var mActivity: Activity

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "kmxy_base")
    channel.setMethodCallHandler(this)
  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    when (call.method) {
      // 直接打电话
      "callPhone" -> {
        callPhone(call.arguments as String)
        result.success("成功")
      }
      // 忽略电池优化
      "requestIgnoreBatteryOptimizations" -> {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
          requestIgnoreBatteryOptimizations()
          result.success("成功")
        }
      }
      // 开启定位服务
      "startLocationService" -> {
        startLocationService()
        result.success("成功")
      }
      // 停止定位服务
      "stopLocationService" -> {
        stopLocationService()
        result.success("成功")
      }
      // 设置开启悬浮窗
      "setSystemAlertWindow" -> {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
          setSystemAlertWindow()
          result.success("成功")
        }
      }
      // 判断是否开启悬浮窗
      "isSystemAlertWindow" -> {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
          result.success(isSystemAlertWindow())
        }
      }
      // 是否忽略电池优化
      "isIgnoringBatteryOptimizations" -> {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
          result.success(isIgnoringBatteryOptimizations())
        }
      }
      // 蒲公英地址
      "pgyerUrl" -> {
          result.success("https://www.pgyer.com")
      }
      else -> result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
    if (locationChangeBroadcastReceiver != null) mActivity.unregisterReceiver(
      locationChangeBroadcastReceiver
    )
  }

  override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    mActivity = binding.activity

    // 保护广播
    val intentFilter = IntentFilter()
    intentFilter.addAction("flutter_cjy_location_in_background")
    mActivity.registerReceiver(locationChangeBroadcastReceiver, intentFilter)
  }

  override fun onDetachedFromActivityForConfigChanges() {
    TODO("Not yet implemented")
  }

  override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    TODO("Not yet implemented")
  }

  override fun onDetachedFromActivity() {
    TODO("Not yet implemented")
  }

  /**
   * 直接拨打电话
   */
  private fun callPhone(num: String) {
    val action = Intent.ACTION_CALL
    val intent = Intent(action)
    intent.data = Uri.parse("tel:$num")
    mActivity.startActivity(intent)
  }

  /**
   * 忽略电池优化
   */
  @RequiresApi(Build.VERSION_CODES.M)
  private fun requestIgnoreBatteryOptimizations() {
    try {
      val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
      intent.data = Uri.parse("package:" + mActivity.packageName)
      mActivity.startActivity(intent)
    } catch (e: Exception) {
      e.printStackTrace()
    }
  }

  /**
   * 是否忽略电池优化
   */
  @RequiresApi(api = Build.VERSION_CODES.M)
  private fun isIgnoringBatteryOptimizations(): Boolean {
    var isIgnoring = false
    val powerManager: PowerManager? = mActivity.getSystemService(Context.POWER_SERVICE) as PowerManager?
    if (powerManager != null) {
      isIgnoring = powerManager.isIgnoringBatteryOptimizations(mActivity.packageName)
    }
    return isIgnoring
  }

  /**
   * 设置开启悬浮窗
   */
  @RequiresApi(Build.VERSION_CODES.M)
  private fun setSystemAlertWindow() {
    if (!isSystemAlertWindow()) {
      val intent = Intent()
      intent.action = Settings.ACTION_MANAGE_OVERLAY_PERMISSION
      intent.data = Uri.parse("package:${mActivity.packageName}")
      mActivity.startActivity(intent)
    }
  }

  /**
   * 判断是否开启悬浮窗
   */
  @RequiresApi(Build.VERSION_CODES.M)
  private fun isSystemAlertWindow(): Boolean {
    return Settings.canDrawOverlays(mActivity)
  }

  /**
   * 定位广播通知过来的定位数据
   */
  private val locationChangeBroadcastReceiver: BroadcastReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
      val action = intent.action
      if (action == "flutter_cjy_location_in_background") {
        var locationResult = intent.getStringExtra("resultJson").toString()
        val errorCode = intent.getIntExtra("errorCode",0)
        val gpsAccuracyStatus = intent.getIntExtra("gpsAccuracyStatus",-1)
        val jsonObject = JSONObject(locationResult)
        jsonObject.put("gpsAccuracyStatus",gpsAccuracyStatus)
        locationResult = jsonObject.toString()
        if (errorCode == AMapLocation.LOCATION_SUCCESS) {
//                    Log.e("mWifiAutoCloseDelegate", "网路正常连接")
//                    Log.e("mWifiAutoCloseDelegate", locationResult.toString())
          channel.invokeMethod("locationServiceCallback", locationResult)
        } else {
//                    Log.e("mWifiAutoCloseDelegate", "网路连接失败")
          // 唤醒屏幕
          PowerManagerUtil.getInstance().wakeUp(mActivity)
        }
      }
    }
  }

  /**
   * 开始定位服务
   */
  private fun startLocationService() {
    mActivity.startService(Intent(mActivity, LocationService::class.java))
    LocationStatusManager.getInstance().resetToInit(mActivity)
  }

  /**
   * 关闭服务
   * 先关闭守护进程，再关闭定位服务
   */
  private fun stopLocationService() {
    mActivity.sendBroadcast(Utils.getCloseBrodecastIntent())
    LocationStatusManager.getInstance().resetToInit(mActivity)
  }
}
